package filter;

import bean.Msg;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebFilter(filterName = "ServletException",urlPatterns = "/dao/update/*")
public class MsgFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletResponse response = (HttpServletResponse)resp;
        Msg msg;
        try{
            chain.doFilter(req, response);
            msg = new Msg("1","success");
        } catch (RuntimeException | ServletException e) {
            msg = new Msg("0","error");
        }
        System.out.println(msg);
        response.getWriter().write(URLEncoder.encode(JSON.toJSONString(msg), StandardCharsets.UTF_8));
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
